#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_FormMisc, COOPGIS_FormAssembly, COOPGIS_FormGeography, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_FormStaker, COOPGIS_FormCostEstimate
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms

def CostEstimate(request):
    ApplicationName=djangoproject.settings.COOPGISCostEstimateApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName) 
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/costestimate.html')
        c = Context({'form': form, 'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c)) 
    QueryContract, QueryCompatibleUnit, QueryStakerWorkOrder, \
                    Adder, Multiplier, QueryShowSummaryReport=COOPGIS_FormCostEstimate.ProcessCostEstimateForm(form, UserNameOrIPAddress)
    NumberOfCostEstimates=10
    COOPGIS_FormCostEstimate.ProcessCostEstimateFormPrices(form, UserNameOrIPAddress, NumberOfCostEstimates, Adder, Multiplier)
    COOPGIS_FormCostEstimate.PopulateCostEstimateForm(form, UserNameOrIPAddress, QueryContract, QueryCompatibleUnit, NumberOfCostEstimates)
    if(QueryShowSummaryReport and Multiplier and Adder):
        CSVPrices=DisplayPriceList(QueryContract, QueryCompatibleUnit, Adder, Multiplier)
    elif(QueryStakerWorkOrder and Multiplier and Adder):
        CSVPrices=CalculatePriceList(QueryContract, QueryStakerWorkOrder, Adder, Multiplier) 
    else:
        CSVPrices=''
    
    t = loader.get_template('/opt/coopgis/djangoproject/templates/costestimate.html')
    c = Context({'form': form, 'LoginStatus':LoginStatus, 'CSVPrices':CSVPrices})
    return HttpResponse(t.render(c))











def CostEstimateContract(request):
    ApplicationName=djangoproject.settings.COOPGISCostEstimateApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName) 
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'Contract')
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/costestimatecontract.html')
        c = Context({'form': form, 'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c)) 
    NumberOfContracts=10
    COOPGIS_FormCostEstimate.ProcessCostEstimateContractForm(form, UserNameOrIPAddress, NumberOfContracts)
    COOPGIS_FormCostEstimate.PopulateCostEstimateContractForm(form, UserNameOrIPAddress, NumberOfContracts)
    #raise(Exception(str(form.data)))
    t = loader.get_template('/opt/coopgis/djangoproject/templates/costestimatecontract.html')
    c = Context({'form': form, 'LoginStatus':LoginStatus})
    return HttpResponse(t.render(c))














def CalculatePriceList(QueryContract, stakerWorkOrder, Adder, Multiplier):
    InstallDictionary = GetInstallAssemblies(stakerWorkOrder)
    RemoveDictionary = GetRemoveAssemblies(stakerWorkOrder)
    TotalInstallPrice=0.0
    TotalRemovePrice=0.0
    Result=[]
    TempResult=[]
    Result.append("**************************Install Costs**************************\n")
    for i in InstallDictionary:
        Quantity=InstallDictionary[i]
        if('.' in str(Quantity)):
            Quantity=round(Quantity, 3)
        Temp, DecodedPrice=GetPrice(i, InstallDictionary[i], QueryContract, Adder, Multiplier, 'Install')
        try:
            TotalInstallPrice=TotalInstallPrice + Temp
        except TypeError:
            pass
        try:
            DecodedPrice=str(int(round(DecodedPrice,0)))
        except TypeError:
            DecodedPrice='No Price'
        TempResult.append(str(i) + ', $' + str(Temp) + ',' + str(Quantity) + ',' + DecodedPrice + '\n')
    TempResult.sort()
    Result = Result + TempResult
    Result.append('\n')
    TempResult=[]
    Result.append("**************************Remove Costs**************************\n")
    for i in RemoveDictionary:
        Quantity=RemoveDictionary[i]
        if('.' in str(Quantity)):
            Quantity=round(Quantity, 3)
        Temp, DecodedPrice=GetPrice(i, RemoveDictionary[i], QueryContract, Adder, Multiplier, 'Remove')
        try:
            TotalRemovePrice=TotalRemovePrice + Temp
        except TypeError:
            pass
        try:
            DecodedPrice=str(int(round(DecodedPrice,0)))
        except TypeError:
            DecodedPrice='No Price'
        TempResult.append(str(i) + ', $' + str(Temp) + ',' + str(Quantity) + ',' + DecodedPrice + '\n')
    TempResult.sort()
    Result=Result+TempResult
    Result.append("Total Install Cost:  " + str(round(TotalInstallPrice, 2)) + '\n')
    Result.append("Total Remove Cost:  " + str(round(TotalRemovePrice, 2)) + '\n')
    Result.append("Total:  " + str(round(TotalInstallPrice + TotalRemovePrice, 2)) + '\n')
    return ''.join(Result)


def GetInstallAssemblies(stakerWorkOrder):
    """Returns Assemblies in Format Results['CompatibleUnitName']= Quantity"""
    Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder).filter(InstallStatus__Name='Install')
    Results={}
    for i in Assemblies:        
        if not i.CompatibleUnit.Name in Results:
            if(i.Station):
                Results[i.CompatibleUnit.Name]=1
            else:
                Results[i.CompatibleUnit.Name]=round(djangoproject.models.staker.GetConductorTotalLength([i], True)/1000,3)
        elif(i.Station):
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + 1
        else:
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + round(djangoproject.models.staker.GetConductorTotalLength([i], True)/1000,3)           
    return Results
    

def GetRemoveAssemblies(stakerWorkOrder):
    """Returns Assemblies in Format Results['CompatibleUnitName']= Quantity"""
    Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder).filter(InstallStatus__Name='Remove')
    Results={}
    for i in Assemblies:
        if not i.CompatibleUnit.Name in Results:
            if(i.Station):
                Results[i.CompatibleUnit.Name]=1
            else:
                Results[i.CompatibleUnit.Name]=round(djangoproject.models.staker.GetConductorTotalLength([i], True)/1000,3)
        elif(i.Station):
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + 1
        else:
            Results[i.CompatibleUnit.Name]=Results[i.CompatibleUnit.Name] + round(djangoproject.models.staker.GetConductorTotalLength([i], True)/1000,3)           
    return Results


def GetPrice(CompatibleUnitName, Quantity, QueryContract, Adder, Multiplier, InstallStatus):
    if(not Multiplier):
        return 'No Multiplier'
    try:
        compatibleUnitPrice=compatibleunit.CompatibleUnitPrice.objects.filter(CompatibleUnit__Name=CompatibleUnitName)
        if(QueryContract):
            compatibleUnitPrice=compatibleUnitPrice.filter(CompatibleUnitPriceContract=QueryContract)
        compatibleUnitPrice=compatibleUnitPrice[0]
    except IndexError:
        compatibleUnitPrice=None
    if(compatibleUnitPrice):
        if(InstallStatus == 'Install'):
            DecodedPrice=int(round((compatibleUnitPrice.CodedInstallPrice / Multiplier) - Adder, 0))
        elif(InstallStatus == 'Remove'):
            DecodedPrice=int(round((compatibleUnitPrice.CodedRemovePrice / Multiplier) - Adder,0))
        return int(round(Quantity * DecodedPrice,0)), DecodedPrice
    else:
        return 'No Price Found', None

def DisplayPriceList(QueryContract, compatibleUnit, Adder, Multiplier):
    try:
        compatibleUnitPrice=compatibleunit.CompatibleUnitPrice.objects.all()
        if(compatibleUnit):
            compatibleUnitPrice=compatibleUnitPrice.filter(CompatibleUnit=compatibleUnit)
        if(QueryContract):
            compatibleUnitPrice=compatibleUnitPrice.filter(CompatibleUnitPriceContract=QueryContract)
    except IndexError:
        return 'No Matching Prices Found'
    ResultList=['Contract'.rjust(20) + 'Compatible Unit'.rjust(25) + 'Install Price'.rjust(15) + 'Remove Price'.rjust(15)]
    compatibleUnitPrice=compatibleUnitPrice.order_by('CompatibleUnit__Name')
    for i in compatibleUnitPrice:
        ResultList.append(str(i.CompatibleUnitPriceContract).rjust(20) + str(i.CompatibleUnit.Name).rjust(25) + 
                          str(round(i.CodedInstallPrice / Multiplier - Adder, 0)).rjust(17)[:-2] + str(round(i.CodedRemovePrice / Multiplier - Adder, 0)).rjust(17)[:-2])
    return '\n'.join(ResultList)

